# * @Author: 刘佳  #  登录页面
# * @Date: 2025-07-17 10:54:57
# * @LastEditTime: 2025-07-17 10:54:57
import json

import pymysql
import requests
from qt_material import apply_stylesheet

from Util.zconfig import get_setting
from PyQt5 import QtGui, QtWidgets, QtCore
from PyQt5.QtWidgets import (
     QDialog, QLineEdit, QCheckBox, QPushButton, QVBoxLayout, QHBoxLayout,
     QLabel, QMessageBox, QFrame, QApplication, QGraphicsDropShadowEffect
 )
from PyQt5.QtGui import QIcon, QFont, QPixmap, QColor, QLinearGradient, QPainter, QPainterPath, QBrush
from PyQt5.QtCore import Qt, QSettings, QSize, QTimer, QPoint, QRectF


class GradientWidget(QFrame):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setObjectName("gradientWidget")
        # # 添加高斯模糊效果
        # self.blur_effect = QtWidgets.QGraphicsBlurEffect()
        # self.blur_effect.setBlurRadius(10)  # 模糊半径
        # self.setGraphicsEffect(self.blur_effect)

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        # 创建淡紫色渐变
        gradient = QLinearGradient(0, 0, self.width(), self.height())
        gradient.setColorAt(0, QColor("#fdf6f0"))  # 雾奶油
        gradient.setColorAt(0.5, QColor("#e4f2f7"))  # 冰薄荷
        gradient.setColorAt(1, QColor("#d6e3f0"))  # 鼠尾草雾青

        # 绘制圆角背景 - 修复：使用 QRectF 替代 QRect
        path = QPainterPath()
        rect = QRectF(0, 0, self.width(), self.height())
        path.addRoundedRect(rect, 15, 15)
        painter.fillPath(path, gradient)


class LoginDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent, Qt.FramelessWindowHint)
        self.weburl = None
        self.dburl = None
        self.setWindowTitle('AutoGet登录')
        self.setFixedSize(800, 494)
        self.setObjectName("LoginDialog")
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(":/logo/1.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.setWindowIcon(icon)
        apply_stylesheet(self, theme='light_blue.xml', invert_secondary=True)

        # 设置窗口背景透明以实现圆角效果
        self.setAttribute(Qt.WA_TranslucentBackground)

        # 创建渐变背景控件
        self.bg_widget = GradientWidget(self)
        self.bg_widget.setGeometry(0, 0, self.width(), self.height())

        # 创建主内容区 - 靠右显示
        self.container = QFrame(self)
        self.container.setGeometry(400, 47, 350, 400)  # 靠右显示
        self.container.setObjectName("container")

        # 添加阴影效果
        shadow = QGraphicsDropShadowEffect()
        shadow.setBlurRadius(20)
        shadow.setColor(QColor(0, 0, 0, 80))
        shadow.setOffset(0, 5)
        self.container.setGraphicsEffect(shadow)

        self.container.setStyleSheet("""
            #container {
                background-color: rgba(255, 255, 255, 0.95);
                border-radius: 15px;
            }
        """)

        # 添加右上角关闭按钮
        self.close_btn = QPushButton("×", self)
        self.close_btn.setGeometry(760, 10, 30, 30)
        self.close_btn.setStyleSheet("""
            QPushButton {
                background-color: rgba(255, 255, 255, 0.5);
                color: #666;
                
                border-radius: 15px;
                font-size: 18px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: red;
                color: white;
            }
        """)
        self.close_btn.clicked.connect(self.close_app)

        # 主布局
        layout = QVBoxLayout(self.container)
        layout.setContentsMargins(30, 30, 30, 30)
        layout.setSpacing(20)

        # 添加标题和图标
        title_layout = QHBoxLayout()
        title_layout.setAlignment(Qt.AlignCenter)
        icon_label = QLabel()
        icon_pixmap = QPixmap(":/logo/1.png").scaled(
            32, 32, Qt.KeepAspectRatio, Qt.SmoothTransformation
        )
        icon_label.setPixmap(icon_pixmap)
        icon_label.setFixedSize(32, 32)  # 关键：固定高度
        title_layout.addWidget(icon_label)

        # 文字
        title_label = QLabel('AutoGet 登录')
        title_label.setFont(QFont("Microsoft YaHei", 20, QFont.Bold))
        title_label.setStyleSheet("color:#4d5c66;")
        title_label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)  # 垂直居中
        title_layout.addWidget(title_label)

        layout.addLayout(title_layout)

        # 输入框样式
        input_style = """
            QLineEdit {
                background-color: #f5f9fc;
                border: 2px solid #e0e6ed;
                border-radius: 8px;
                padding: 12px 15px;
                font-size: 14px;
                color: #333;
            }
            QLineEdit:focus {
                border-color: #a3c4d9;
            }
            QLineEdit:placeholder {
                color: #aaa;
            }
        """

        # 用户名输入框
        self.username_input = QLineEdit()
        self.username_input.setPlaceholderText('请输入用户名')
        self.username_input.setStyleSheet(input_style)
        self.username_input.setMinimumHeight(45)
        layout.addWidget(QLabel("用户名"))
        layout.addWidget(self.username_input)

        # 密码输入框
        self.password_input = QLineEdit()
        self.password_input.setPlaceholderText('请输入密码')
        self.password_input.setEchoMode(QLineEdit.Password)
        self.password_input.setStyleSheet(input_style)
        self.password_input.setMinimumHeight(45)
        layout.addWidget(QLabel("密码"))
        layout.addWidget(self.password_input)

        # 选项布局
        options_layout = QHBoxLayout()

        # 记住密码
        self.remember_cb = QCheckBox("记住密码")
        self.remember_cb.setFont(QFont("Microsoft YaHei", 10))
        self.remember_cb.setStyleSheet("color: #666;")
        options_layout.addWidget(self.remember_cb)

        # 自动登录
        self.auto_login_cb = QCheckBox("自动登录")
        self.auto_login_cb.setFont(QFont("Microsoft YaHei", 10))
        self.auto_login_cb.setStyleSheet("color: #666;")
        self.auto_login_cb.toggled.connect(self._on_auto_login_toggled)
        # 初始判断一次
        self._on_auto_login_toggled(self.auto_login_cb.isChecked())
        options_layout.addWidget(self.auto_login_cb)

        layout.addLayout(options_layout)

        # 登录按钮
        self.login_btn = QPushButton('登 录')
        self.login_btn.setMinimumHeight(45)
        self.login_btn.setFont(QFont("Microsoft YaHei", 12, QFont.Bold))
        self.login_btn.setStyleSheet("""
            QPushButton {
                background-color: #a3c4d9;
                color: white;
                border: 1px solid #7aa2bb;
                border-radius: 8px;
                padding: 10px;
            }
            QPushButton:hover {
                background-color: #8fb3cc;
            }
            QPushButton:pressed {
                background-color: #7aa2bb;
            }
            QPushButton:disabled {
                background-color: #d6e3f0;
            }
        """)
        self.login_btn.clicked.connect(self.handle_login)
        layout.addWidget(self.login_btn)

        # 底部信息
        footer_label = QLabel('© 2025 AutoGet 数据获取工具  By:刘佳')
        footer_label.setAlignment(Qt.AlignCenter)
        footer_label.setFont(QFont("Microsoft YaHei", 8))
        footer_label.setStyleSheet("color: #999; margin-top: 10px;")
        layout.addWidget(footer_label)

        # 加载设置
        self.settings = QSettings("EasyStudio", "StoreDataApp")
        self.load_settings()

        # 自动登录延迟处理
        # if self.auto_login_cb.isChecked():
        #     QTimer.singleShot(3000, self.handle_login)

        # 输入变化时验证
        self.username_input.textChanged.connect(self.validate_inputs)
        self.password_input.textChanged.connect(self.validate_inputs)
        self.validate_inputs()  # 初始验证

        # 应用样式表
        self.setStyleSheet("""
            QDialog {
                background: transparent;
            }
            QLabel {
                color: #555;
            }
            QCheckBox::indicator {
                width: 16px;
                height: 16px;
            }
            QCheckBox::indicator:checked {
                background-color: #a3c4d9;
                border: 1px solid #8fb3cc;
                border-radius: 3px;
            }
        """)

    def validate_inputs(self):
        """验证用户名和密码是否已输入"""
        username = self.username_input.text().strip()
        password = self.password_input.text().strip()

        # 启用/禁用登录按钮
        self.login_btn.setEnabled(bool(username and password))

        # 设置输入框样式提示
        input_style_base = """
            background-color: #f5f9fc;
            border-radius: 8px;
            padding: 12px 15px;
            font-size: 14px;
            color: #333;
        """

        if not username:
            self.username_input.setStyleSheet(f"QLineEdit {{ {input_style_base} border: 2px solid #e9a9a9; }}")
        else:
            self.username_input.setStyleSheet(f"QLineEdit {{ {input_style_base} border: 2px solid #e0e6ed; }}")

        if not password:
            self.password_input.setStyleSheet(f"QLineEdit {{ {input_style_base} border: 2px solid #e9a9a9; }}")
        else:
            self.password_input.setStyleSheet(f"QLineEdit {{ {input_style_base} border: 2px solid #e0e6ed; }}")

    def close_app(self):
        """关闭应用程序"""
        QApplication.quit()

    def load_settings(self):
        username = self.settings.value("username", "")
        password = self.settings.value("password", "")
        remember = self.settings.value("remember", True, type=bool)
        auto_login = self.settings.value("auto_login", False, type=bool)

        self.username_input.setText(username)
        if remember:
            self.password_input.setText(password)
        self.remember_cb.setChecked(remember)
        self.auto_login_cb.setChecked(auto_login)

    def _on_auto_login_toggled(self, checked):
        """勾选/取消勾选时自动启动/停止登录定时器"""
        if checked:
            # 如果已有则复用，没有就新建
            if not hasattr(self, '_auto_login_timer') or self._auto_login_timer is None:
                self._auto_login_timer = QTimer(self)
                self._auto_login_timer.setSingleShot(True)
                self._auto_login_timer.timeout.connect(self.handle_login)
            self._auto_login_timer.start(3000)
        else:
            if hasattr(self, '_auto_login_timer') and self._auto_login_timer is not None:
                self._auto_login_timer.stop()

    def handle_login(self):
        """处理登录逻辑"""
        username = self.username_input.text().strip()
        password = self.password_input.text().strip()

        # 必填验证
        if not username or not password:
            if not username:
                self.username_input.setFocus()
            else:
                self.password_input.setFocus()

            QMessageBox.warning(self, '输入错误', '用户名和密码不能为空！')
            return

        if self.checkUserInDb(username, password):
            # 登录成功
            if self.remember_cb.isChecked():
                self.settings.setValue("username", username)
                self.settings.setValue("password", password)
            else:
                self.settings.setValue("username", "")
                self.settings.setValue("password", "")
            self.settings.setValue("remember", self.remember_cb.isChecked())
            self.settings.setValue("auto_login", self.auto_login_cb.isChecked())
            self.accept()
        else:
            QMessageBox.critical(self, '提示', '用户名或密码错误，或用户未激活')

    # 添加鼠标拖动支持
    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.drag_start_position = event.globalPos() - self.frameGeometry().topLeft()
            event.accept()

    def mouseMoveEvent(self, event):
        if event.buttons() == Qt.LeftButton and hasattr(self, 'drag_start_position'):
            self.move(event.globalPos() - self.drag_start_position)
            event.accept()

    def checkUserInDb(self, username, password):
        z_debug =  get_setting('DEBUG')
        if z_debug:
            self.dburl = get_setting('DBURL')['DEV']
            self.weburl = get_setting('WEBURL')['DEV']
        else:
            self.dburl = get_setting('DBURL')['PRD']
            self.weburl = get_setting('WEBURL')['PRD']

        url = self.weburl + "/api/login/"
        headers = {"Content-Type": "application/json"}
        payload = {"username": username, "password": password}

        try:
            resp = requests.post(url, data=json.dumps(payload), headers=headers, timeout=5)
            result = resp.json()
            return result.get("ok", False)
        except Exception as e:
            print("网络或服务器错误:", e)
            return False
